import path from "path";
import {
  app,
  dialog,
  ipcMain,
  BrowserWindow,
  BrowserWindowConstructorOptions,
  session,
} from "electron";
import fs from "fs";
import appState from "../../app-state";
import WindowBase from "../window-base";
import FramelessWindow from "../frameless";
import axiosInst from "../../../lib/axios-inst/main";
import XLSX from "xlsx";
import axios from "axios";

class PrimaryWindow extends WindowBase {
  private cookie: string = ""; // 添加cookie属性
  private autoSubmitTimer: NodeJS.Timeout | null = null; // 添加定时器属性

  constructor() {
    super({
      width: 1200,
      height: 800,
      webPreferences: {
        preload: path.join(__dirname, "preload.js"),
        webSecurity: false,
        allowRunningInsecureContent: true,
      },
    });

    this._browserWindow?.on("close", (e) => {
      // 允许窗口正常关闭
      if (this.autoSubmitTimer) {
        clearTimeout(this.autoSubmitTimer);
        this.autoSubmitTimer = null;
      }
      appState.allowExitApp = true;
    });
    this.openRouter("/primary");
  }

  /**
   * 执行自动化操作
   */
  private async executeAutomationTasks() {
    try {
      console.log("开始执行自动化任务");

      // 模拟各种自动化任务的执行
      // 在实际应用中，可以在这里添加真正的自动化操作代码

      // 模拟异步操作
      await new Promise((resolve) => setTimeout(resolve, 5000));

      return {
        success: true,
        message: "自动化任务执行成功",
      };
    } catch (error) {
      console.error("自动化任务执行失败:", error);
      return {
        success: false,
        message: error instanceof Error ? error.message : "未知错误",
      };
    }
  }

  /**
   * 读取Excel文件
   */
  private async readExcelFile(filePath: string) {
    try {
      // 读取文件内容
      const fileContent = fs.readFileSync(filePath);

      // 使用xlsx库解析Excel文件
      const workbook = XLSX.read(fileContent);
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];

      // 将工作表转换为JSON数据
      const jsonData = XLSX.utils.sheet_to_json(worksheet);

      // 如果没有数据，提前返回
      if (!jsonData || jsonData.length === 0) {
        return {
          success: false,
          data: [],
          message: "Excel文件中没有找到任何数据",
        };
      }

      // 输出第一行数据的列名，用于调试
      const firstRow = jsonData[0] as Record<string, unknown>;
      const columns = Object.keys(firstRow);
      console.log("Excel文件列名:", columns);

      // 处理数据，保留所有列
      const data = jsonData.map((row: any, index: number) => {
        const rowData: Record<string, any> = {};
        columns.forEach((column) => {
          rowData[column] = row[column] || "";
        });
        return rowData;
      });

      return {
        success: true,
        data,
        columns,
        message: `成功读取${data.length}条数据`,
      };
    } catch (error) {
      console.error("读取Excel文件失败:", error);
      return {
        success: false,
        data: [],
        columns: [],
        message:
          error instanceof Error
            ? `读取Excel文件失败: ${error.message}`
            : "读取Excel文件时发生未知错误",
      };
    }
  }

  /**
   * 自动登录并获取Cookie
   */
  private async autoLoginGetCookie(options: {
    loginUrl: string;
    username: string;
    password: string;
  }): Promise<{ success: boolean; cookie?: string; message?: string }> {
    let loginWindow: BrowserWindow | null = null;

    try {
      console.log("开始自动登录流程");
      const { loginUrl, username, password } = options;

      // 创建一个新的浏览器窗口用于登录
      loginWindow = new BrowserWindow({
        width: 800,
        height: 600,
        show: false, // 设置为不显示窗口
        webPreferences: {
          nodeIntegration: false,
          contextIsolation: true,
          webSecurity: false,
          allowRunningInsecureContent: true,
          webviewTag: true,
        },
      });

      // 在加载URL之前设置CSP
      loginWindow.webContents.session.webRequest.onHeadersReceived(
        (details, callback) => {
          callback({
            responseHeaders: {
              ...details.responseHeaders,
              "Content-Security-Policy": [
                "default-src 'self' 'unsafe-inline' 'unsafe-eval' http: https: data: blob:",
              ],
            },
          });
        }
      );

      // 添加Cookie变化监听
      loginWindow.webContents.session.cookies.on(
        "changed",
        (event, cookie, cause, removed) => {
          console.log("Cookie changed:", {
            name: cookie.name,
            value: cookie.value,
            cause,
            removed,
          });
        }
      );

      // 设置一个标志来跟踪是否已处理了cookie
      let cookieProcessed = false;
      let resultResolve:
        | ((value: {
            success: boolean;
            cookie?: string;
            message?: string;
          }) => void)
        | null = null;

      // 创建一个Promise来等待结果
      const resultPromise = new Promise<{
        success: boolean;
        cookie?: string;
        message?: string;
      }>((resolve) => {
        resultResolve = resolve;
      });

      // 监听页面加载错误
      loginWindow.webContents.on(
        "did-fail-load",
        (event, errorCode, errorDescription) => {
          console.error("页面加载失败:", { errorCode, errorDescription });
          if (resultResolve) {
            resultResolve({
              success: false,
              message: `页面加载失败: ${errorDescription}`,
            });
          }
        }
      );

      // 监听网页加载完成事件
      loginWindow.webContents.on("did-finish-load", async () => {
        if (!loginWindow) return;

        const currentUrl = loginWindow.webContents.getURL();
        console.log("当前页面URL:", currentUrl);

        if (currentUrl.includes("login") && !cookieProcessed) {
          console.log("注入登录脚本...");
          try {
            await loginWindow.webContents.executeJavaScript(`
              const fillForm = async () => {
                try {
                  console.log("等待登录表单元素加载...");
                  
                  // 更精确的选择器来查找输入框
                  const usernameInput = document.querySelector('input[placeholder="手机号/登录名"]') || 
                                      document.querySelector('input[placeholder*="手机号"]') ||
                                      document.querySelector('input[type="text"]');
                  
                  if (usernameInput) {
                    console.log("找到用户名输入框");
                    usernameInput.value = "${username}";
                    usernameInput.dispatchEvent(new Event('input', { bubbles: true }));
                    usernameInput.dispatchEvent(new Event('change', { bubbles: true }));
                  } else {
                    console.error("未找到用户名输入框");
                  }
                  
                  // 更精确的选择器来查找密码框
                  const passwordInput = document.querySelector('input[placeholder="请输入密码"]') ||
                                      document.querySelector('input[type="password"]');
                  
                  if (passwordInput) {
                    console.log("找到密码输入框");
                    passwordInput.value = "${password}";
                    passwordInput.dispatchEvent(new Event('input', { bubbles: true }));
                    passwordInput.dispatchEvent(new Event('change', { bubbles: true }));
                  } else {
                    console.error("未找到密码输入框");
                  }
                  
                  // 使用ID选择器查找提交按钮
                  const submitButton = document.querySelector('#submitButton') ||
                                     document.querySelector('button:contains("授权登录")') ||
                                     document.querySelector('button.login-button') ||
                                     Array.from(document.querySelectorAll('button')).find(btn => btn.textContent.includes('授权'));
                  
                  if (submitButton) {
                    console.log("找到提交按钮");
                    // 等待一段时间确保表单值已经被框架处理
                    setTimeout(() => {
                      console.log("点击登录按钮");
                      submitButton.click();
                    }, 1500);
                  } else {
                    console.error("未找到提交按钮");
                  }
                } catch (error) {
                  console.error("填写表单失败:", error);
                }
              };

              // 等待页面完全加载后执行
              if (document.readyState === 'complete') {
                fillForm();
              } else {
                window.addEventListener('load', fillForm);
              }
            `);
          } catch (error) {
            console.error("注入登录脚本失败:", error);
          }
        }
      });

      // 监听导航完成事件
      loginWindow.webContents.on("did-navigate", async (_, url) => {
        if (!loginWindow) return;

        console.log("导航到新URL:", url);

        if (url.includes("bsdts.chinaetc.org/ass") && !cookieProcessed) {
          console.log("检测到登录成功，等待Cookie设置完成...");

          // 等待一段时间确保所有Cookie都已设置
          await new Promise((resolve) => setTimeout(resolve, 5000));

          try {
            // 获取所有Cookie
            const cookies = await loginWindow.webContents.session.cookies.get(
              {}
            );
            console.log(
              "获取到的所有Cookie:",
              cookies.map((c) => ({ name: c.name, value: c.value }))
            );

            // 尝试从URL中获取SESSION
            const sessionMatch = url.match(/SESSION=([^&;]+)/);
            if (sessionMatch) {
              console.log("从URL中找到SESSION:", sessionMatch[1]);
              // 手动设置SESSION cookie
              await loginWindow.webContents.session.cookies.set({
                url: "http://bsdts.chinaetc.org",
                name: "SESSION",
                value: sessionMatch[1],
                domain: ".chinaetc.org",
                path: "/",
              });
            }

            // 再次获取所有Cookie确保包含SESSION
            const finalCookies =
              await loginWindow.webContents.session.cookies.get({});
            const cookieString = finalCookies
              .filter((cookie) =>
                ["SESSION", "JSESSIONID", "SERVERID"].includes(cookie.name)
              )
              .map((cookie) => `${cookie.name}=${cookie.value}`)
              .join("; ");

            if (!cookieString.includes("SESSION=")) {
              throw new Error("未能获取SESSION Cookie");
            }

            console.log("最终Cookie字符串:", cookieString);

            // 更新axios和类属性中的Cookie
            axios.defaults.headers.common["Cookie"] = cookieString;
            this.cookie = cookieString;

            if (resultResolve) {
              resultResolve({
                success: true,
                cookie: cookieString,
                message: "登录成功并获取Cookie",
              });
            }

            // 立即关闭窗口
            if (loginWindow) {
              loginWindow.close();
              loginWindow = null;
            }
          } catch (error) {
            console.error("处理Cookie失败:", error);
            if (resultResolve) {
              resultResolve({
                success: false,
                message:
                  error instanceof Error
                    ? error.message
                    : "获取Cookie失败，请重试",
              });
            }
          }
        }
      });

      // 设置超时处理
      setTimeout(() => {
        if (!cookieProcessed && resultResolve) {
          console.log("登录操作超时");
          resultResolve({
            success: false,
            message: "自动登录超时，请稍后重试",
          });

          if (loginWindow) {
            loginWindow.close();
            loginWindow = null;
          }
        }
      }, 30000);

      // 加载登录页面
      if (!loginWindow) {
        throw new Error("登录窗口创建失败");
      }

      await loginWindow.loadURL(loginUrl);

      // 打开开发者工具便于调试
      if (process.env.NODE_ENV === "development" && loginWindow) {
        loginWindow.webContents.openDevTools();
      }

      return await resultPromise;
    } catch (error: any) {
      console.error("自动登录获取Cookie失败:", error);
      if (loginWindow) {
        loginWindow.close();
        loginWindow = null;
      }
      return {
        success: false,
        message: error.message || "自动登录失败，请稍后重试",
      };
    }
  }

  /**
   * 设置定时提交
   */
  private async setAutoSubmitTimer(
    scheduledTime: string
  ): Promise<{ success: boolean; message: string }> {
    try {
      // 清除已存在的定时器
      if (this.autoSubmitTimer) {
        clearTimeout(this.autoSubmitTimer);
        this.autoSubmitTimer = null;
      }

      // 解析预定时间
      const scheduledDateTime = new Date(scheduledTime);
      const now = new Date();

      // 计算延迟时间（毫秒）
      const delay = scheduledDateTime.getTime() - now.getTime();

      if (delay < 0) {
        return {
          success: false,
          message: "设定的时间已经过去，请选择将来的时间",
        };
      }

      // 计算提前一分钟的时间点，用于刷新Cookie
      const refreshCookieTime = scheduledDateTime.getTime() - 1 * 60 * 1000;
      const refreshDelay = refreshCookieTime - now.getTime();

      // 计算提前5秒的时间点，用于发起请求
      const requestTime = new Date(scheduledDateTime.getTime() - 5 * 1000);
      const requestDelay = requestTime.getTime() - now.getTime();

      // 如果距离执行时间不足一分钟，则立即刷新Cookie
      if (refreshDelay <= 0) {
        if (this._browserWindow) {
          console.log("立即触发自动获取Cookie");
          this._browserWindow.webContents.send("trigger-auto-login");
        }
      } else {
        // 设置提前一分钟的定时器来刷新Cookie
        setTimeout(() => {
          if (this._browserWindow) {
            console.log("定时任务将在1分钟后执行，开始自动获取Cookie...");
            this._browserWindow.webContents.send("trigger-auto-login");
          }
        }, refreshDelay);
      }

      // 如果距离执行时间不足5秒，则立即开始发起请求
      if (requestDelay <= 0) {
        if (this._browserWindow) {
          console.log("立即触发自动发起请求");
          this._browserWindow.webContents.send("trigger-create-work-order");
        }
      } else {
        // 设置提前5秒的定时器来开始发起请求
        setTimeout(() => {
          if (this._browserWindow) {
            console.log("定时任务将在5秒后执行，开始发起请求...");
            this._browserWindow.webContents.send("trigger-create-work-order");
          }
        }, requestDelay);
      }

      // 设置定时器（实际上已经在提前5秒时开始执行了，这里只是为了完整性保留）
      this.autoSubmitTimer = setTimeout(async () => {
        try {
          console.log("定时任务时间到达");
          // 发送状态更新通知
          if (this._browserWindow) {
            this._browserWindow.webContents.send("auto-submit-status", {
              success: true,
              message: "定时任务已执行完成",
            });
          }
        } catch (error) {
          console.error("定时任务执行失败:", error);
          if (this._browserWindow) {
            this._browserWindow.webContents.send("auto-submit-status", {
              success: false,
              message:
                error instanceof Error ? error.message : "定时任务执行失败",
            });
          }
        }
      }, delay);

      const scheduledTimeStr = scheduledDateTime.toLocaleString();
      return {
        success: true,
        message: `定时任务已设置，将在 ${scheduledTimeStr} 自动执行 (会提前1分钟自动获取Cookie，提前5秒开始发起请求)`,
      };
    } catch (error) {
      console.error("设置定时任务失败:", error);
      return {
        success: false,
        message: error instanceof Error ? error.message : "设置定时任务失败",
      };
    }
  }

  /**
   * 取消定时提交
   */
  private cancelAutoSubmit(): { success: boolean; message: string } {
    if (this.autoSubmitTimer) {
      clearTimeout(this.autoSubmitTimer);
      this.autoSubmitTimer = null;
      return {
        success: true,
        message: "定时任务已取消",
      };
    }
    return {
      success: false,
      message: "没有正在运行的定时任务",
    };
  }

  private generateAttachCode(): string {
    const now = new Date();
    const timestamp =
      now.getFullYear().toString() +
      (now.getMonth() + 1).toString().padStart(2, "0") +
      now.getDate().toString().padStart(2, "0") +
      now.getHours().toString().padStart(2, "0") +
      now.getMinutes().toString().padStart(2, "0") +
      now.getSeconds().toString().padStart(2, "0") +
      now.getMilliseconds().toString().padStart(3, "0");

    // 生成一个随机数字字符串
    const random = Math.floor(Math.random() * 1000000000000000000)
      .toString()
      .padStart(12, "0");

    return timestamp + random;
  }

  /**
   * 上传图片文件
   */
  private async uploadImage(
    imagePath: string,
    options?: {
      fileName?: string;
      attachName?: string;
    }
  ): Promise<{
    success: boolean;
    attachCode?: string;
    message?: string;
    fileName?: string;
  }> {
    try {
      const formData = new FormData();
      const attachCode = this.generateAttachCode();

      // 读取文件
      const fileBuffer = fs.readFileSync(imagePath);
      const blob = new Blob([fileBuffer]);

      // 获取文件名
      const fileName =
        options?.fileName || path.basename(imagePath) || "dbc.png";

      // 设置表单数据
      formData.append("file", blob, fileName);
      formData.append("attachName", options?.attachName || fileName || "");
      formData.append("attachType", "4");
      formData.append("attachLabel", "1");
      formData.append("attachCode", attachCode);
      formData.append("orderId", "");
      formData.append("remark", "");
      formData.append("origin", "1");

      // 发送请求
      const response = await axios.post(
        "http://bsdts.chinaetc.org/ass/order-attach/files",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Cookie: this.cookie,
            "User-Agent":
              "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
            Referer: "http://bsdts.chinaetc.org/ass/auditProcess/collect",
            Origin: "http://bsdts.chinaetc.org",
            Host: "bsdts.chinaetc.org",
          },
        }
      );

      console.log("上传图片文件响应:", response);

      if (response.status === 200) {
        return {
          success: true,
          attachCode,
          message: "PDF文件上传成功",
          fileName: fileName,
        };
      } else {
        throw new Error(`上传失败: ${response.statusText}`);
      }
    } catch (error) {
      console.error("上传文件失败:", error);
      return {
        success: false,
        message: error instanceof Error ? error.message : "上传失败",
      };
    }
  }

  protected registerIpcMainHandler(): void {
    ipcMain.on("message", (event, message) => {
      if (!this.isIpcMainEventBelongMe(event)) return;
      console.log(message);
    });

    ipcMain.on("show-frameless-sample-window", (event) => {
      if (!appState.framelessWindow?.valid) {
        appState.framelessWindow = new FramelessWindow();
      }

      const win = appState.framelessWindow?.browserWindow;
      if (win) {
        // 居中到父窗体中
        const parent = win.getParentWindow();
        if (parent) {
          const parentBounds = parent.getBounds();
          const x = Math.round(
            parentBounds.x + (parentBounds.width - win.getSize()[0]) / 2
          );
          const y = Math.round(
            parentBounds.y + (parentBounds.height - win.getSize()[1]) / 2
          );

          win.setPosition(x, y, false);
        }
        win.show();
      }
    });

    function delay(time) {
      return new Promise((resolve) => setTimeout(resolve, time));
    }

    ipcMain.on("min-to-tray", (event) => {
      if (!this.isIpcMainEventBelongMe(event)) return;

      if (process.platform == "win32") {
        this.browserWindow?.hide();
      } else {
        // macos or other
        this.browserWindow?.minimize();
      }

      if (appState.tray) {
        appState.tray.displayBalloon({
          title: "electron-vue-",
          content: "客户端已经最小化到系统托盘!",
        });
      }
    });

    ipcMain.handle("async-exit-app", async (event) => {
      // 暂停1500毫秒，模拟退出程序时的清理操作
      await delay(1500);
      appState.allowExitApp = true;
      app.quit();
    });

    ipcMain.on("http-get-request", (event, url) => {
      axiosInst
        .get(url)
        .then((rsp) => {
          dialog.showMessageBox(this._browserWindow!, {
            message: `在主进程中请求 ${url} 成功！状态码：${rsp.status}`,
            type: "info",
          });
        })
        .catch((err) => {
          dialog.showMessageBox(this._browserWindow!, {
            message: `在主进程中请求 ${url} 失败！错误消息：${err.message}`,
            type: "error",
          });
        });
    });

    // 注册自动化API处理函数
    ipcMain.handle("run-automation", async () => {
      try {
        // 打开开发者工具
        if (this.browserWindow) {
          this.browserWindow.webContents.openDevTools();
        }

        // 执行自动化任务
        await this.executeAutomationTasks();
        return {
          success: true,
          message: "自动化任务执行成功",
        };
      } catch (error: any) {
        console.error("自动化任务执行失败:", error);
        return {
          success: false,
          message: error.message || "未知错误",
        };
      }
    });

    // 注册Excel文件读取处理函数
    ipcMain.handle("read-excel-file", async (event, filePath) => {
      return await this.readExcelFile(filePath);
    });

    ipcMain.handle("submit-traffic-data", async (event, submitData) => {
      try {
        console.log("开始提交数据:", submitData);

        // 创建自定义的 axios 实例
        const instance = axios.create({
          timeout: 60000, // 增加超时时间到60秒
          maxRedirects: 5,
          validateStatus: (status) => status < 400,
          headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
            Cookie:
              axios.defaults.headers.common["Cookie"] ||
              "JSESSIONID=8A52C1B4962AE58570AB107E7C73866D; SESSION=Mzc0ODE1YzUtMGUxYi00ZjI2LThlZDEtMDk4NzY3YTJlNWJj; SERVERID=82fe9baeb662d8e5e93e3d4b59b0b4a3|1741150134|1741144599",
            "User-Agent":
              "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
            Referer: "http://bsdts.chinaetc.org/ass/auditProcess/collect",
            Origin: "http://bsdts.chinaetc.org",
            Host: "bsdts.chinaetc.org",
          },
        });

        // 添加请求拦截器，用于调试
        instance.interceptors.request.use(
          (config) => {
            console.log("发送请求配置:", {
              url: config.url,
              method: config.method,
              headers: config.headers,
              data: config.data,
            });
            return config;
          },
          (error) => {
            console.error("请求拦截器错误:", error);
            return Promise.reject(error);
          }
        );

        // 添加响应拦截器，用于调试
        instance.interceptors.response.use(
          (response) => {
            console.log("收到响应:", {
              status: response.status,
              headers: response.headers,
              data: response.data,
            });
            return response;
          },
          (error) => {
            console.error("响应拦截器错误:", error);
            return Promise.reject(error);
          }
        );

        // 发送请求
        const response = await instance.post(
          "http://bsdts.chinaetc.org/ass/auditProcess/collect",
          submitData,
          {
            proxy: false,
            httpsAgent: false,
            httpAgent: false,
            decompress: true, // 启用响应解压
          }
        );

        console.log("API响应状态:", response.status);
        console.log("API响应头:", response.headers);
        console.log("API响应数据:", response.data);

        // 检查响应内容类型
        const contentType = response.headers["content-type"];
        if (contentType && contentType.includes("text/html")) {
          throw new Error("会话已过期，请重新登录");
        }

        // 检查响应数据
        if (
          typeof response.data === "string" &&
          response.data.includes("<!DOCTYPE html>")
        ) {
          throw new Error("会话已过期，请重新登录");
        }

        return {
          success: true,
          data: response.data,
          message: "提交成功",
        };
      } catch (error: any) {
        console.error("提交数据失败:", error);
        console.error("错误详情:", {
          message: error.message,
          code: error.code,
          response: error.response?.data,
          status: error.response?.status,
          stack: error.stack,
        });

        // 处理特定的错误情况
        if (error.code === "ECONNABORTED") {
          throw new Error("连接超时，请检查网络连接和防火墙设置");
        }

        if (error.code === "ECONNREFUSED") {
          throw new Error("连接被拒绝，请检查服务器地址是否正确");
        }

        if (error.response?.status === 302 || error.response?.status === 301) {
          throw new Error("会话已过期，请重新登录");
        }

        throw new Error(
          error.response?.data?.message ||
            error.message ||
            "提交失败，请检查网络连接"
        );
      }
    });

    // 添加专门用于打开开发者工具的处理程序
    ipcMain.handle("open-devtools", () => {
      console.log("开发者工具请求接收到");
      if (this.browserWindow) {
        console.log("正在打开开发者工具");
        this.browserWindow.webContents.openDevTools();
        return true;
      }
      console.log("browserWindow不存在，无法打开开发者工具");
      return false;
    });

    // 添加获取Cookie的处理程序
    ipcMain.handle(
      "get-cookie",
      async (_, options: { url: string; name: string }) => {
        return await this.getCookie(options);
      }
    );

    // 添加更新Cookie的处理程序
    ipcMain.handle("update-cookie", async (event, cookieString) => {
      try {
        console.log("更新Cookie:", cookieString);
        // 更新axios实例的默认Cookie和类属性
        axios.defaults.headers.common["Cookie"] = cookieString;
        this.cookie = cookieString; // 更新类属性
        return {
          success: true,
          message: "Cookie更新成功",
        };
      } catch (error) {
        console.error("更新Cookie失败:", error);
        return {
          success: false,
          message: error instanceof Error ? error.message : "更新Cookie失败",
        };
      }
    });

    // 处理工单创建请求
    ipcMain.handle("create-work-order", async (_, data) => {
      try {
        console.log("正在创建工单...");
        const response = await axios.post(
          "http://bsdts.chinaetc.org/ass/orderProcess/create",
          data,
          {
            headers: {
              "Content-Type": "application/json",
              Accept: "application/json",
              Cookie: axios.defaults.headers.common["Cookie"] || "",
              "User-Agent":
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
              Referer: "http://bsdts.chinaetc.org/ass/auditProcess/collect",
              Origin: "http://bsdts.chinaetc.org",
              Host: "bsdts.chinaetc.org",
            },
          }
        );

        if (response.status === 200) {
          console.log("工单创建成功:", response.data);
          return {
            success: true,
            data: response.data,
          };
        } else {
          console.error("工单创建失败:", response.status, response.statusText);
          return {
            success: false,
            message: `创建失败: ${response.statusText}`,
          };
        }
      } catch (error: any) {
        console.error("工单创建出错:", error);
        const errorMessage =
          error.response?.data?.message || error.message || "未知错误";
        return {
          success: false,
          message: `创建失败: ${errorMessage}`,
        };
      }
    });

    // 添加自动登录获取Cookie的处理程序
    ipcMain.handle("auto-login-get-cookie", async (_, options) => {
      return await this.autoLoginGetCookie(options);
    });

    // 添加设置定时提交的处理程序
    ipcMain.handle("set-auto-submit", async (_, scheduledTime: string) => {
      return await this.setAutoSubmitTimer(scheduledTime);
    });

    // 添加取消定时提交的处理程序
    ipcMain.handle("cancel-auto-submit", () => {
      return this.cancelAutoSubmit();
    });

    // 添加electron相关IPC通道
    ipcMain.on("open-dev-tools", () => {
      if (this._browserWindow) {
        this._browserWindow.webContents.openDevTools();
      }
    });

    // 修改图片上传处理程序
    ipcMain.handle("upload-image", async (_, options) => {
      try {
        console.log("upload-image 处理程序开始执行，接收到的选项:", options);

        // 检查Cookie是否有效
        if (!this.cookie || this.cookie.trim() === "") {
          console.error("Cookie为空，无法上传文件");
          return {
            success: false,
            message: "Cookie为空，请先登录或设置Cookie",
          };
        }

        console.log("当前使用的Cookie:", this.cookie);

        let imagePath;
        let fileName;
        let attachName;
        let fileData;

        // 如果提供了选项，使用选项中的值
        if (options && typeof options === "object") {
          console.log("检测到选项对象:", Object.keys(options));
          imagePath = options.filePath;
          fileName = options.fileName;
          attachName = options.attachName;
          fileData = options.fileData; // 新增：接收文件数据

          console.log("解析选项:", {
            hasFilePath: !!imagePath,
            hasFileName: !!fileName,
            hasAttachName: !!attachName,
            hasFileData: !!fileData,
            fileDataLength: fileData ? fileData.length : 0,
          });
        }

        // 如果提供了文件数据，直接使用它
        if (fileData) {
          console.log("检测到文件数据，准备直接上传");

          // 将Base64转换为Buffer
          const base64Data = fileData.split(",")[1]; // 移除Base64前缀
          console.log("Base64数据长度:", base64Data.length);

          const fileBuffer = Buffer.from(base64Data, "base64");
          console.log("转换后的Buffer长度:", fileBuffer.length);

          // 生成attachCode
          const attachCode = this.generateAttachCode();
          console.log("生成的attachCode:", attachCode);

          // 创建FormData
          const formData = new FormData();
          formData.append("file", new Blob([fileBuffer]), fileName);
          formData.append("attachName", attachName || fileName);
          formData.append("attachType", "4");
          formData.append("attachLabel", "1");
          formData.append("attachCode", attachCode);
          formData.append("orderId", "");
          formData.append("remark", "");
          formData.append("origin", "1");

          console.log("准备发送请求，FormData已准备好");
          console.log("请求头中的Cookie:", this.cookie);

          try {
            // 发送请求
            console.log("开始发送POST请求");
            const response = await axios.post(
              "http://bsdts.chinaetc.org/ass/order-attach/files",
              formData,
              {
                headers: {
                  "Content-Type": "multipart/form-data",
                  Cookie: this.cookie,
                  "User-Agent":
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
                  Referer: "http://bsdts.chinaetc.org/ass/auditProcess/collect",
                  Origin: "http://bsdts.chinaetc.org",
                  Host: "bsdts.chinaetc.org",
                },
                maxRedirects: 0, // 禁止自动重定向
              }
            );

            console.log("收到响应状态码:", response.status);

            // 检查响应是否包含HTML（可能是登录页面）
            const isHtmlResponse =
              typeof response.data === "string" &&
              (response.data.includes("<!DOCTYPE html>") ||
                response.data.includes("<html>"));

            if (isHtmlResponse) {
              console.error(
                "服务器返回了HTML页面，可能是登录页面，Cookie可能已过期"
              );
              return {
                success: false,
                message: "Cookie已过期，请重新登录",
              };
            }

            console.log("上传文件响应数据:", response.data);

            if (response.status === 200) {
              console.log("上传成功，返回结果");
              return {
                success: true,
                attachCode,
                message: "PDF文件上传成功",
                fileName: fileName,
              };
            } else {
              console.log("上传失败，状态码不是200");
              throw new Error(`上传失败: ${response.statusText}`);
            }
          } catch (error: any) {
            console.error("发送请求时出错:", error);

            // 检查是否是重定向错误（状态码302）
            if (error.response && error.response.status === 302) {
              console.error("服务器返回了重定向，Cookie可能已过期");
              return {
                success: false,
                message: "Cookie已过期，请重新登录",
              };
            }

            throw error;
          }
        }

        // 如果没有提供文件路径和文件数据，打开文件选择对话框
        else if (!imagePath) {
          console.log("没有提供文件路径和文件数据，打开文件选择对话框");

          const result = await dialog.showOpenDialog({
            properties: ["openFile"],
            filters: [
              { name: "所有文件", extensions: ["*"] },
              { name: "文档文件", extensions: ["doc", "docx", "pdf", "txt"] },
              { name: "图片文件", extensions: ["jpg", "jpeg", "png", "gif"] },
            ],
          });

          console.log("文件选择结果:", result);

          if (result.canceled || result.filePaths.length === 0) {
            console.log("用户取消了文件选择");
            return { success: false, message: "未选择文件" };
          }

          imagePath = result.filePaths[0];
          console.log("选择的文件路径:", imagePath);

          // 如果没有提供文件名，使用选择的文件的文件名
          if (!fileName) {
            fileName = path.basename(imagePath);
            console.log("使用文件名:", fileName);
          }

          // 如果没有提供attachName，使用文件名
          if (!attachName) {
            attachName = fileName;
            console.log("使用attachName:", attachName);
          }

          console.log("调用uploadImage函数上传文件");
          // 只有在没有提供文件数据时，才调用uploadImage函数
          return await this.uploadImage(imagePath, { fileName, attachName });
        }
        // 如果提供了文件路径但没有提供文件数据，直接调用uploadImage函数
        else {
          console.log(
            "提供了文件路径但没有提供文件数据，直接调用uploadImage函数"
          );
          return await this.uploadImage(imagePath, { fileName, attachName });
        }
      } catch (error) {
        console.error("上传文件失败:", error);
        return {
          success: false,
          message: error instanceof Error ? error.message : "上传失败",
        };
      }
    });
  }

  /**
   * 提交数据的方法
   */
  private async submitTrafficData(
    submitData: any
  ): Promise<{ success: boolean; message?: string }> {
    try {
      console.log("开始提交数据:", submitData);

      const instance = axios.create({
        timeout: 60000,
        maxRedirects: 5,
        validateStatus: (status) => status < 400,
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          Cookie: this.cookie,
          "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
          Referer: "http://bsdts.chinaetc.org/ass/auditProcess/collect",
          Origin: "http://bsdts.chinaetc.org",
          Host: "bsdts.chinaetc.org",
        },
      });

      const response = await instance.post(
        "http://bsdts.chinaetc.org/ass/auditProcess/collect",
        submitData
      );

      if (response.status === 200) {
        return {
          success: true,
          message: "数据提交成功",
        };
      } else {
        throw new Error(`提交失败: ${response.statusText}`);
      }
    } catch (error) {
      console.error("提交数据失败:", error);
      return {
        success: false,
        message: error instanceof Error ? error.message : "提交失败",
      };
    }
  }

  /**
   * 获取Cookie
   */
  private async getCookie(options: {
    url: string;
    name: string;
  }): Promise<string | null> {
    if (this._browserWindow) {
      try {
        const cookies =
          await this._browserWindow.webContents.session.cookies.get({
            url: options.url,
            name: options.name,
          });
        if (cookies.length > 0) {
          return cookies[0].value;
        }
      } catch (error) {
        console.error("获取Cookie失败:", error);
      }
    }
    return null;
  }
}

export default PrimaryWindow;
